package com.topsec.manager.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.topsec.manager.common.Constants;
import com.topsec.manager.common.Model;
import com.topsec.manager.common.ReqResultData;
import com.topsec.manager.controller.req.*;
import com.topsec.manager.entity.*;
import com.topsec.manager.service.ReleaseServiceInter;
import com.topsec.manager.socket.MyWebSocket;
import com.topsec.manager.socket.WebSocketMapUtil;
import com.topsec.manager.util.*;
import com.topsec.manager.vo.HttpxyVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 工具controller
 *
 * @author zhaoys
 * @date 2017年7月22日 下午3:47:23
 */
@Controller
public class ReleaseController {
	// 日志记录器
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private ReleaseServiceInter releaseService;


	/**
	 * 添加工具测试结果
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	@ResponseBody
	public String test() {
		log.info("测试是否用的log4j4");
		try {
			System.out.println("成功");
			throw  new Exception("测试 log.error 的打印规则");
		} catch (Exception e) {
			log.error("测试失败" + e.getMessage());
		}
		return "success";
	}

	/**
	 * 通信检测
	 */
	@RequestMapping(value = "/sys/test", method = RequestMethod.GET)
	@ResponseBody
	public String sysTest(String key) {
		NatReq n = new NatReq();
		try {
			// 将数据以流的方式写入文件中
			ObjectOutputStream dot = new ObjectOutputStream(
					new FileOutputStream(Constants.W_S_REQUEST + "system" + key + ".test"));
			dot.writeObject(n);
			dot.close();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("系统通信测试异常" + e.getMessage());
		}
		return null;
	}

	/**
	 * 查询主机snat配置
	 */
	@RequestMapping(value = "/nat/query", method = RequestMethod.POST)
	@ResponseBody
	public String natQuery(@RequestBody NatReq n) {
		try {
			// 将数据以流的方式写入文件中
			ObjectOutputStream dot = new ObjectOutputStream(
					new FileOutputStream(Constants.W_S_REQUEST + "nat_" + n.getKey() + ".request"));
			dot.writeObject(n);
			dot.close();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询nat配置失败" + e.getMessage());
		}
		return JsonUtil.json(n);
	}

	@RequestMapping(value = "/nat/update", method = RequestMethod.POST)
	@ResponseBody
	public String natUp(@RequestBody NatReq n) {
		try {
			// 将数据以流的方式写入文件中
			ObjectOutputStream dot = new ObjectOutputStream(
					new FileOutputStream(Constants.W_S_REQUEST + "nat_" + n.getKey() + ".request"));
			dot.writeObject(n);
			dot.close();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询nat配置失败" + e.getMessage());
		}
		return JsonUtil.json(n);
	}

	/**
	 * 根据id查询版本
	 */
	@RequestMapping(value = "/versions/findbyid", method = RequestMethod.POST)
	@ResponseBody
	public String versionsFindByid(@RequestBody VersionReq v) {
		List<VersionVo> list = new ArrayList<VersionVo>();
		try {
			list = releaseService.findVersionByid(v.getId());
		} catch (Exception e) {
			log.error("查询版本失败" + e.getMessage());
		}
		return JsonUtil.json(list);
	}

	/**
	 * 查询所有版本
	 */
	@RequestMapping(value = "/versions/findall", method = RequestMethod.POST)
	@ResponseBody
	public String versionfind(@RequestBody VersionReq v) {
		String result = "";
		try {
			List<VersionVo> findVersion = releaseService.findVersion(v);
			result = JsonUtil.json(findVersion);
		} catch (Exception e) {
			log.error("添加版本异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 工具验证重复存在
	 *
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "/tools/checkTools", method = RequestMethod.POST)
	@ResponseBody
	public String checkToolsRepeat(@RequestBody List<ToolReq> t) {

		System.out.println("=>>> 第三方厂商推送的工具信息：" + t);
		String s = "error";
		try {
			// List<CTCSVersionReq> t = JsonUtil.unjson2(aoData, new
			// TypeToken<List<CTCSVersionReq>>() {
			// }.getType());

			String json = JsonUtil.json(t);
			Gson gson = new Gson();
			List<ToolReq> l = gson.fromJson(json, new TypeToken<List<ToolReq>>() {
			}.getType());
			s = releaseService.checkToolsRepeat(l);
			System.out.println("=>>> 验证工具是否存在的结果：" + s);
		} catch (Exception e) {
			log.error("验证工具是否存在异常" + e.getMessage());
		}
		return s;

	}

	/**
	 * 查询所有工具
	 */
	@RequestMapping(value = "/tools/findall", method = RequestMethod.GET)
	@ResponseBody
	public String toolfind() {
		String result = "";
		try {
			List<ToolBo> findTool = releaseService.findTool();
			result = JsonUtil.json(findTool);
		} catch (Exception e) {
			log.error("添加工具异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 根据id查询工具
	 */
	@RequestMapping(value = "/tools/findbyid", method = RequestMethod.POST)
	@ResponseBody
	public String toolsfindByid(@RequestBody ToolReq t) {
		List<ToolBo> list = new ArrayList<ToolBo>();
		try {
			list = releaseService.findToolByid(t.getId());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询工具失败" + e.getMessage());
		}
		return JsonUtil.json(list);
	}

	/**
	 * 参数验证
	 *
	 * @param t
	 * @return
	 */
	private boolean checkParam(ToolReq t) {
		boolean res = true;
		if ("".equals(t.getToolname()) || t.getToolname() == null) {
			res = false;
			return res;
		} else if ("".equals(t.getUrl()) || t.getUrl() == null) {
			res = false;
			return res;
		} else if ("".equals(t.getVersionnumber()) || t.getVersionnumber() == null) {
			res = false;
			return res;
		} else if ("".equals(t.getPlatform()) || t.getPlatform() == null) {
			res = false;
			return res;
		} else if ("".equals(t.getIcopath()) || t.getIcopath() == null) {
			res = false;
			return res;
		}
		return res;
	}

	/**
	 * 说明：验证工具的url是否存在
	 *
	 * @param tUrl
	 *            要验证的工具的url
	 * @return reBl false表示url存在
	 * @author hyq
	 * @date 2018/12/11 9:49
	 */
	private boolean checkToolUrl(List<ToolBo> toolList, String tUrl) {
		boolean reBl = true;
		try {
			List<String> urlList = new ArrayList<>();
			for (ToolBo vo : toolList) {
				String url = vo.getUrl();
				urlList.add(url);
			}

			String urlMarket = SplitToolUrlUtil.getUrlMarket(tUrl);
			// 暂时只验证官方市场的url
			if ("play.google".equals(urlMarket) || "itunes.apple".equals(urlMarket)
					|| "chrome.google".equals(urlMarket)) {
				List<String> urlIdList = SplitToolUrlUtil.getAllUrlIdList(urlList, urlMarket);
				String url = SplitToolUrlUtil.splitToolUrl(tUrl, urlMarket);
				List<String> checkList = new ArrayList<>();
				for (String s : urlIdList) {
					if (s.equals(url)) {
						checkList.add(s);
					}
				}
				if (checkList.size() > 0) {
					reBl = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("验证工具是否重复失败" + e.getMessage());
		}
		return reBl;
	}

	/**
	 * 新工具发现
	 */
	@RequestMapping(value = "/tools/add", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData toolAdd(@RequestBody ToolReq t) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ReqResultData result = new ReqResultData();
		try {
			if (checkParam(t)) {
				List<ToolBo> list = releaseService.findTool();
				List<ToolBo> list1 = releaseService.findTool1();
				boolean checkToolUrl = checkToolUrl(list, t.getUrl());
				boolean checkToolUrl2 = checkToolUrl(list1, t.getUrl());
				if (checkToolUrl == false || checkToolUrl2 == false) {
					t.setIsaudit("4");
					result.setStatus(-1);
					result.setMsg("Adding Tool fail,repeat");
					String info = "发现新工具[" + t.getToolname() + "]在工具库中已经存在";
					SystemLogger log = new SystemLogger("warn", Model.getName(1), info, sf.format(new Date()), null);
					releaseService.saveLogger(log);
				}
				releaseService.saveTool(t);
			} else {
				result.setStatus(0);
				result.setMsg("Parameter error(工具名称,版本号,平台,url,图标不能为空)");

			}
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("Adding Tool Errors");
			log.error("添加工具异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 新版本发现
	 */
	@RequestMapping(value = "/tversion/add", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData toolVersionAdd(@RequestBody VersionReq v) {
		ReqResultData result = new ReqResultData();
		try {
			releaseService.saveTVersion(v);
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("Adding Version Errors");
			log.error("添加工具版本异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 工具跟踪
	 */
	@RequestMapping(value = "/tversion/following", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData toolFollowing(@RequestBody ToolReq t) {
		ReqResultData result = new ReqResultData();
		try {
			releaseService.versionFollowing(t);
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("工具跟踪下发异常" + e.getMessage());
			log.error("工具跟踪下发异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 下发多条工具(可能list中就工具分类不同，其他信息一样)跟踪
	 */
	@RequestMapping(value = "/tversion/followings", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData toolFollowings(@RequestBody List<ToolReq> t) {
		ReqResultData result = new ReqResultData();
		try {
			System.out.println("进入多条工具跟踪");
			String json = JsonUtil.json(t);
			Gson gson = new Gson();
			List<ToolReq> l = gson.fromJson(json, new TypeToken<List<ToolReq>>() {
			}.getType());

			releaseService.versionFollowings(l);
			System.out.println("17发送多条工具跟踪成功");
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("多条工具跟踪下发异常" + e.getMessage());
			log.error("多条工具跟踪下发异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 添加设备信息
	 */
	@RequestMapping(value = "/device/addDeviceInfo", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData addDeviceInfo(@RequestBody Sys_RunState deviceInfo) {
		ReqResultData result = new ReqResultData();
		try {
			releaseService.saveDeviceInfo(deviceInfo);
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("添加设备信息异常" + e.getMessage());
			log.error("添加设备信息异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 查询有效资源
	 */
	@RequestMapping(value = "/ctresource/add", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData saveCtresource(@RequestBody Ctresource c) {
		ReqResultData result = new ReqResultData();
		try {
			releaseService.saveCtresource(c);
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("查询有效资源信息异常" + e.getMessage());
			log.error("查询有效资源信息异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 添加工具测试结果
	 *
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "/tooltest/add", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData toolTest(@RequestBody ToolTestBean t) {
		ReqResultData result = new ReqResultData();
		try {
			releaseService.saveToolTest(t);
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("添加工具测试结果信息异常" + e.getMessage());
			log.error("添加工具测试结果信息异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * ssl客户端的全量查询
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/sslCert/getdata", method = RequestMethod.GET)
	@ResponseBody
	public ReqResultData getSslCertData(String data) {
		ReqResultData reqResultData = new ReqResultData();
		String result = "";
		Gson gson = new Gson();
		try {
			List<SslCertQueryVO> chelloData = releaseService.getSslCertData(data);
			// String json = c
			reqResultData.setData(chelloData);
		} catch (Exception e) {
			reqResultData.setStatus(0);
			reqResultData.setMsg("查询数据失败" + e.getMessage());
			log.error("查询数据失败" + e.getMessage());
		}
		return reqResultData;
	}

	/**
	 * ssl客户端的全量查询
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/cHello/getdata", method = RequestMethod.GET)
	@ResponseBody
	public ReqResultData getCHelloData(String data) {
		ReqResultData reqResultData = new ReqResultData();
		String result = "";
		Gson gson = new Gson();
		try {
			List<CHelloQueryVO> chelloData = releaseService.getChelloData(data);
			// String json = JsonUtil.json(httpXyData);
			reqResultData.setData(chelloData);
		} catch (Exception e) {
			reqResultData.setStatus(0);
			reqResultData.setMsg("查询数据失败" + e.getMessage());
			log.error("查询数据失败" + e.getMessage());
		}
		return reqResultData;
	}

	/**
	 * 添加工具测试结果
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/httpxy/getdata", method = RequestMethod.GET)
	@ResponseBody
	public ReqResultData getHttpxyData(String data) {
		ReqResultData reqResultData = new ReqResultData();
		String result = "";
		Gson gson = new Gson();
		try {
			List<HttpxyVO> httpXyData = releaseService.getHttpXyData(data);
			// String json = JsonUtil.json(httpXyData);
			reqResultData.setData(httpXyData);
		} catch (Exception e) {
			reqResultData.setStatus(0);
			reqResultData.setMsg("查询数据失败" + e.getMessage());
			log.error("查询数据失败" + e.getMessage());
		}
		return reqResultData;
	}


	/**
	 * 17发送版本穿透测试
	 */
	@RequestMapping(value = "/cttest/sendversions", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData sendVersCTCSting(@RequestBody List<CTCSVersionReq> t) {

		System.out.println("=>>> 17接受穿透测试数据：" + t);

		ReqResultData result = new ReqResultData();
		try {
			// List<CTCSVersionReq> t = JsonUtil.unjson2(aoData, new
			// TypeToken<List<CTCSVersionReq>>() {
			// }.getType());

			String json = JsonUtil.json(t);
			Gson gson = new Gson();
			List<CTCSVersionReq> l = gson.fromJson(json, new TypeToken<List<CTCSVersionReq>>() {
			}.getType());
			releaseService.saveSendVersionTest(l);
			System.out.println("=>>> 17接受穿透测试数据生成指令成功");
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("版本下发穿透测试异常" + e.getMessage());
			log.error("版本下发穿透测试异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 外网请求接V生成版本穿透测试指令
	 */
	@RequestMapping(value = "/cttest/resversions", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData resVersCTCSting(@RequestBody List<CTCSVersionReq> t) {
		ReqResultData result = new ReqResultData();
		try {

			String json = JsonUtil.json(t);
			Gson gson = new Gson();
			List<CTCSVersionReq> l = gson.fromJson(json, new TypeToken<List<CTCSVersionReq>>() {
			}.getType());
			releaseService.saveResVersionTest(l);
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("版本接V网收穿透测试异常" + e.getMessage());
			log.error("版本V网穿透测试异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 信工所更新Dns任务完成状态
	 */
	@RequestMapping(value = "/updnstask/xinstatus", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData upXinDnsTaskStutas(@RequestBody DnsAndIp_TaskReq d) {
		System.out.println("=>>> 信工所更改DNS任务状态 =>>> id：" + d.getId());
		System.out.println("=>>> 信工所更改DNS任务状态 =>>> status：" + d.getXinStatus());
		System.out.println("=>>> 信工所更改DNS任务状态 =>>> count：" + d.getCount());

		ReqResultData result = new ReqResultData();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
			String format = sdf.format(new Date());
			Task_DnsVo dnsById = releaseService.findDnsById(d.getId());
			String commitTime = dnsById.getCommitTime();

			String i = DateUtil.secBetween(commitTime, format);
			d.setTimes(i);
			String count = d.getCount();
			if (StringUtils.isNotEmpty(count) && null != count) {
				String nums = NumUtil.delNumerals(Long.parseLong(d.getCount()));
				d.setCount(nums);
			} else {
				d.setCount("--");
			}

			int i1 = releaseService.upXinDnsTask(d);
			if (i1 > 0) {
				String taskcreator = dnsById.getTaskcreator(); // 任务创建者
				String querystr = dnsById.getQuerystr(); // 查询内容
				boolean b = ValidateUtils.IP4(querystr);
				String sendMsg = taskcreator;
				if (b) {
					sendMsg = sendMsg + ",ip";
				} else {
					sendMsg = sendMsg + ",dns";
				}

				MyWebSocket socket = WebSocketMapUtil.get(taskcreator);
				if (null != socket) {
					socket.onMessage(sendMsg);
				}
			}
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("=>>> 信工所更新Dns任务完成状态异常" + e.getMessage());
			log.error("=>>> 信工所更新Dns任务完成状态异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 天元特通更新Dns任务完成状态
	 */
	@RequestMapping(value = "/updnstask/tianstatus", method = RequestMethod.POST)
	@ResponseBody
	public ReqResultData upTianDnsTaskStutas(@RequestBody DnsAndIp_TaskReq d) {
		System.out.println("=>>> 天元特通更改DNS任务状态 =>>> id：" + d.getId());
		System.out.println("=>>> 天元特通更改DNS任务状态 =>>> status：" + d.getTianStatus());
		System.out.println("=>>> 天元特通更改DNS任务状态 =>>> count：" + d.getCount());

		ReqResultData result = new ReqResultData();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
			String format = sdf.format(new Date());
			Task_DnsVo dnsById = releaseService.findDnsById(d.getId());
			String commitTime = dnsById.getCommitTime();

			String i = DateUtil.secBetween(commitTime, format);
			d.setTimes(i);
			String count = d.getCount();
			if (StringUtils.isNotEmpty(count) && null != count) {
				String nums = NumUtil.delNumerals(Long.parseLong(d.getCount()));
				d.setCount(nums);
			} else {
				d.setCount("--");
			}

			int i1 = releaseService.upTianDnsTask(d);
			if (i1 > 0) {
				String taskcreator = dnsById.getTaskcreator(); // 任务创建者
				String querystr = dnsById.getQuerystr(); // 查询内容
				boolean b = ValidateUtils.IP4(querystr);
				String sendMsg = taskcreator;
				if (b) {
					sendMsg = sendMsg + ",ip";
				} else {
					sendMsg = sendMsg + ",dns";
				}

				MyWebSocket socket = WebSocketMapUtil.get(taskcreator);
				if (null != socket) {
					socket.onMessage(sendMsg);
				}
			}
		} catch (Exception e) {
			result.setStatus(0);
			result.setMsg("天元特通更新Dns任务完成状态异常" + e.getMessage());
			log.error("天元特通更新Dns任务完成状态异常" + e.getMessage());
		}
		return result;
	}

	/**
	 * 处理历史数据的图片格式
	 */
	@RequestMapping(value = "/dealImageType", method = RequestMethod.GET)
	@ResponseBody
	public String dealImageType() {
		String msg = "success";
		try {
			System.out.println(" ===>>> 进入处理工具方法：dealImageType");
			// 本地-正式工具图片的地址
			String toolPath = "/topsec/web/tomcat/webapps/topsec-web/WEB-INF/classes/static/images/tool/";
			File file = new File(toolPath);
			File[] files = file.listFiles();
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					System.out.println(" ===>>> 处理正式工具图片格式");
					if (files[i].isFile()) {
						String fileName = files[i].getName();
						String allPath = toolPath + fileName;
						ImageUtil.dealImageType(allPath, allPath);
					}
				}
			}
		} catch (Exception e) {
			msg = "error";
		}
		return msg;
	}
}
